<?php

class UploadController extends GdgUploadAppController {
    
    public $uses = array();
    
    public function upload() {
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $path = $_POST['path'];
        $file = $this->request->params['form']['file'];
        if($file['error'] > 0){
            $this->set("result", json_encode(array('error'=>'Upload server error code: ' . $file['error'])));
            return;
        }
        App::uses('String', 'Utility');
        
        require_once(ROOT . DS . APP_DIR . '/Plugin/GdgUpload/Config/Config.php');

        if ($path == null) {
            $path = Configure::read('gdg.upload.defaults.directory');
        }
        if(strpos('/', $path) !== 0){
            $path = WWW_ROOT . $path;
        }
        if(substr($path, -1) != '/'){
            $path .= '/';
        }
        
        $ext = strrchr($file['name'], '.');
        
        $filename = String::uuid();
        $filename .= $ext;
        
        $newFilePath = $path . $filename;
        
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        if(!move_uploaded_file($file['tmp_name'], $newFilePath)){
            $this->set("result", json_encode(array('error'=>'Unable to move file to destination folder: ' . $newFilePath)));
            return;
        }
        
        $this->set("result", json_encode(array('file'=> $filename)));
    }
}
?>
